<script setup>
import {inject} from 'vue'
import {getDateTimeFormatNow} from "@/utils/DateUtils.js";
import { showImagePreview } from 'vant';
import 'vant/es/image-preview/style';
import {showConfirmDialog} from 'vant';
import 'vant/es/dialog/style'
import {delLiuById} from "@/api/liu.js";

const refresh = inject('refresh')

const props = defineProps({
  liu: {type: Object, default: {}},
  showDel: {type: Boolean, default: false},
})

const imgPreview = (imgIdx) => {
  showImagePreview({
    images: props.liu.imgs.map(
        item => item.imgUrl
    ),
    startPosition: imgIdx,
  });
}

const onDel = () => {
  showConfirmDialog({
    message: '是否确认删除留言'
  }).then(async () => {
    // on confirm
    const res = await delLiuById(props.liu.id)
    if (res) {
      await refresh()
    }
  }).catch(() => {
    // on cancel
  });
}
</script>

<template>
  <div class="product-comment m-2 p-2 rounded-lg bg-white dark:bg-neutral-900 dark:text-gray-100">
    <div class="flex justify-between items-start">
      <div class="avatar-username flex justify-start">
        <div class="avatar w-12 h-12 mr-4">
          <img class="w-full h-full object-cover rounded-full" :src="liu?.avatar" alt="">
        </div>
        <div>
          <div class="username">
            <span class="">{{ liu?.username }}</span>
          </div>
          <div class="time text-sm text-gray-400">
            {{ getDateTimeFormatNow(liu?.createTime) }}
          </div>
        </div>
      </div>
      <div v-if="showDel">
        <van-button @click="onDel" type="danger" plain size="small">删除</van-button>
      </div>
    </div>
    <div class="comment mt-2">
      <span>{{liu?.content}}</span>
    </div>
    <div class="comment-img-box mt-2">
      <div class="w-24 h-24"
           v-for="(img, imgIdx) in (liu?.imgs.length > 9 ? liu?.imgs.slice(0, 9) : liu?.imgs)"
           @click.stop="imgPreview(imgIdx)">
        <img class="w-full h-full object-contain" :src="img?.imgUrl" alt="">
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.comment-img-box {
  display: grid;
  // 列数自动填充，列宽最小为 24rem，最大占1份平均grid容器宽度
  grid-template-columns: repeat(auto-fill, minmax(6rem, 1fr));
  grid-auto-flow: row; // 容器元素按顺序自动放置，默认先行后列
  column-gap: 1rem; // 列间距
  row-gap: 1rem; // 行间距
  justify-items: center; // 单元格内元素水平位置
  align-items: start; // 单元格内元素垂直位置
}
</style>